import sys
import os
import getpath 
from PyQt5 import QtGui, QtCore,QtWidgets
 
class MyListModel(QtCore.QAbstractListModel): 
    def __init__(self, datain, parent=None, *args): 
        """ datain: a list where each item is a row
        """
        QtCore.QAbstractListModel.__init__(self, parent, *args) 
        self.listdata = datain

    def rowCount(self, parent=QtCore.QModelIndex()): 
        return len(self.listdata) 
 
    def data(self, index, role):
        s = QtCore.QSize(170, 100)
        if index.isValid() and role == QtCore.Qt.DecorationRole:
            return QtGui.QImage(self.listdata[index.row()].scaled(s))
        # if index.isValid() and role == QtCore.Qt.DisplayRole:
        #     return QtCore.QVariant(os.path.splitext(os.path.split(self.listdata[index.row()])[-1])[0])
        # else: 
        #     return QtCore.QVariant()
    def addOne(self,pixmap):
        i=len(self.listdata)
        self.beginInsertRows(QtCore.QModelIndex(), i, i)
        self.listdata.append(pixmap) 
        self.endInsertRows()
    def delete_row(self,i):
        if (len(self.listdata) == 0):
            return 
        i = min([max([0, i]), len(self.listdata) - 1])  # Clamp i to a valid object index.
        self.beginRemoveRows(QtCore.QModelIndex(), i, i)
        del self.listdata[i:i+1]
        self.endRemoveRows()
    def delete_item_all(self):        
        self.beginRemoveRows(QtCore.QModelIndex(), 0,len(self.listdata))
        self.listdata=[]
        self.endRemoveRows()
class ImageView(QtWidgets.QListView):
    """docstring for MyListView"""
    def __init__(self):
        super().__init__()
        # show in Icon Mode
        self.setViewMode(QtWidgets.QListView.IconMode)
        # crntDir = os.path.join(getpath.getpath(),"images")
        # create table
        self.list_data = []
        # philes = os.listdir(crntDir)
        # for phile in philes:
        #     if phile.endswith(".png") or phile.endswith("jpg"):
        #         fn=os.path.join(crntDir, phile)
        #         pixmap=QtGui.QPixmap(fn)
        #         self.list_data.append(pixmap)
        #         break
        self.lm = MyListModel(self.list_data, self)
        self.setModel(self.lm)
        self.show()
    def addImage(self,pixmap):
        self.lm.addOne(pixmap)
        pass
    def contextMenuEvent(self, event):
        # 右键菜单事件
        # print(self.selectedIndexes())
        num = self.currentIndex()
        row = num.row()
        print(row)
        # it = self.rowAt(pos.y())  # 根据鼠标坐标获取列号
        # logging.info(it)
        # item = self.itemAt(self.mapFromGlobal(QtGui.QCursor.pos()))
        # if not item: return  # 判断是否是空白区域
        menu = QtWidgets.QMenu()
        delete_action = QtWidgets.QAction('删除', self)
        # delete_action.triggered.connect(lambda: self.delete_row(row))  # 传递额外值
        menu.addAction(delete_action)
        delete_all_action = QtWidgets.QAction('删除全部', self)
        # delete_all_action.triggered.connect(self.delete_item_all)  # 传递额外值
        menu.addAction(delete_all_action)
        action = menu.exec_(self.mapToGlobal(event.pos()))
        if action == delete_action:
            self.delete_row(row)
        elif action == delete_all_action:
            self.delete_item_all()
    def delete_row(self,row):
        self.lm.delete_row(row)
        pass
    def delete_item_all(self):
        self.lm.delete_item_all()
if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = ImageView()
    window.show()
    window.raise_()
    sys.exit(app.exec_())